﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using CosyTrade.Core;
using CosyTrade.Data;

namespace CosyTrade.Server
{
    class Program
    {
        private static readonly string defaultDbConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dbConfig.xml");
        static void Main(string[] args)
        {
            AddinServices services = AddinServices.Instance;
            services.InitalizeAddin();
            InitOrm();
            services.StartAddin();

            do
            {
                Console.Write("Server is Running, Press 'exit' to Exit.\r\n>");
            } while (Console.ReadLine() != "exit");

            services.Stop();
        }

        static void InitOrm()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            List<Type> regTypes = new List<Type>();
            foreach (Assembly assembly in assemblies)
            {
                Type[] assemblyTypes = assembly.GetTypes();
                foreach (Type assemblyType in assemblyTypes)
                {
                    if (assemblyType.IsDefined(typeof(ActiveRecordAttribute), false) &&
                        !assemblyType.IsDefined(typeof(NotAutoRegister), false))
                        regTypes.Add(assemblyType);
                }
            }
            XmlConfigurationSource source = new XmlConfigurationSource(defaultDbConfigPath);
            ActiveRecordStarter.Initialize(source, regTypes.ToArray());
        }
    }
}
